import React, { useState, useEffect } from 'react';
import { http, API_PATH } from '../utils/http/config';
import dayjs from 'dayjs';

// 定义用户注册响应类型
interface RegisterResponse {
    code: number;
    message: string;
    data: {
        username: string;
        email: string;
        role: string;
        display_name: string;
    };
}

// 定义用户信息类型
interface UserInfo {
    username: string;
    email: string;
    display_name: string;
    status: string;
    id: string;
    created_at: number;
    updated_at: number;
}

// 定义分页参数类型
interface PaginationParams {
    current: number;
    pageSize: number;
    total: number;
}

// 定义当前用户信息类型
interface CurrentUser {
    username: string;
    email: string;
    display_name: string;
    status: string;
    id: string;
    role: string;
    created_at: number;
    updated_at: number;
}

const UserManagement: React.FC = () => {
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [loading, setLoading] = useState(false);
    const [users, setUsers] = useState<UserInfo[]>([]);
    const [pagination, setPagination] = useState<PaginationParams>({
        current: 1,
        pageSize: 10,
        total: 0
    });
    const [tableLoading, setTableLoading] = useState(false);
    const [toast, setToast] = useState<{ message: string; type: 'success' | 'error' | 'info'; visible: boolean }>({
        message: '',
        type: 'info',
        visible: false
    });
    const [formData, setFormData] = useState({
        username: '',
        password: '',
        confirmPassword: '',
        email: '',
        display_name: '',
    });
    const [formErrors, setFormErrors] = useState<Record<string, string>>({});
    const [currentUser, setCurrentUser] = useState<CurrentUser | null>(null);

    // 显示Toast
    const showToast = (message: string, type: 'success' | 'error' | 'info' = 'info') => {
        setToast({ message, type, visible: true });
        // 自动关闭
        setTimeout(() => {
            setToast(prev => ({ ...prev, visible: false }));
        }, 2000);
    };

    // 获取用户列表
    const fetchUsers = async (page = pagination.current, pageSize = pagination.pageSize) => {
        try {
            setTableLoading(true);
            const params = {
                page,
                page_size: pageSize
            };

            const response = await http.get<UserInfo>(API_PATH.AUTH.USERS, params);

            response.onSuccess(() => {
                setUsers(response.list);
                const meta = response.meta;
                if (meta) {
                    setPagination(prev => ({
                        ...prev,
                        current: meta.page,
                        pageSize: meta.page_size,
                        total: meta.total
                    }));
                }
            }).onError((_, msg) => {
                console.error(`获取用户列表失败: 消息: ${msg}`);
                showToast(`获取用户列表失败: ${msg}`, 'error');
            });

        } catch (error) {
            console.error('网络请求异常:', error);
            showToast('网络请求异常', 'error');
        } finally {
            setTableLoading(false);
        }
    };

    // 处理分页变化
    const handlePageChange = (newPage: number) => {
        setPagination(prev => ({ ...prev, current: newPage }));
    };

    // 页面加载时获取用户列表
    useEffect(() => {
        fetchUsers();
    }, [pagination.current, pagination.pageSize]);

    // 获取当前用户信息
    const fetchCurrentUser = async () => {
        try {
            const response = await http.get<CurrentUser>(API_PATH.AUTH.ME);
            response.onSuccess(() => {
                setCurrentUser(response.data);
            });
        } catch (error) {
            console.error('获取当前用户信息异常:', error);
        }
    };

    // 页面加载时获取当前用户信息
    useEffect(() => {
        fetchCurrentUser();
    }, []);

    const goBack = () => {
        window.location.href = '/';
    };

    // 显示添加用户弹窗
    const showAddUserModal = () => {
        setIsModalVisible(true);
    };

    // 关闭弹窗
    const handleCancel = () => {
        setFormData({
            username: '',
            password: '',
            confirmPassword: '',
            email: '',
            display_name: '',
        });
        setFormErrors({});
        setIsModalVisible(false);
    };

    // 处理表单输入
    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setFormData(prev => ({ ...prev, [name]: value }));
        // 清除对应字段的错误
        if (formErrors[name]) {
            setFormErrors(prev => ({ ...prev, [name]: '' }));
        }
    };

    // 验证表单
    const validateForm = () => {
        const errors: Record<string, string> = {};

        if (!formData.username) {
            errors.username = '请输入用户名';
        } else if (formData.username.length < 3) {
            errors.username = '用户名至少3个字符';
        }

        if (!formData.display_name) {
            errors.display_name = '请输入显示名称';
        }

        if (!formData.password) {
            errors.password = '请输入密码';
        } else if (formData.password.length < 6) {
            errors.password = '密码至少6个字符';
        }

        if (!formData.confirmPassword) {
            errors.confirmPassword = '请确认密码';
        } else if (formData.password !== formData.confirmPassword) {
            errors.confirmPassword = '两次输入的密码不一致';
        }

        if (!formData.email) {
            errors.email = '请输入邮箱';
        } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
            errors.email = '请输入有效的邮箱地址';
        }

        setFormErrors(errors);
        return Object.keys(errors).length === 0;
    };

    // 提交表单
    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!validateForm()) {
            return;
        }

        try {
            setLoading(true);
            const response = await http.post<RegisterResponse>(API_PATH.AUTH.REGISTER, {
                username: formData.username,
                password: formData.password,
                email: formData.email,
                display_name: formData.display_name
            });

            response.onSuccess(() => {
                showToast('用户创建成功', 'success');
                handleCancel();
                fetchUsers();
            }).onError((_, msg) => {
                showToast(`创建失败: ${msg}`, 'error');
            });
        } catch (error) {
            console.error('用户创建错误:', error);
            showToast('提交失败，请检查表单和网络连接', 'error');
        } finally {
            setLoading(false);
        }
    };

    // 生成分页按钮
    const renderPaginationButtons = () => {
        const totalPages = Math.ceil(pagination.total / pagination.pageSize);
        const currentPage = pagination.current;
        const buttons = [];

        // 上一页按钮
        buttons.push(
            <button
                key="prev"
                onClick={() => handlePageChange(currentPage - 1)}
                disabled={currentPage === 1}
                className="px-3 py-1 rounded-md border border-gray-300 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
            >
                上一页
            </button>
        );

        // 页码按钮
        for (let i = 1; i <= totalPages; i++) {
            if (
                i === 1 ||
                i === totalPages ||
                (i >= currentPage - 2 && i <= currentPage + 2)
            ) {
                buttons.push(
                    <button
                        key={i}
                        onClick={() => handlePageChange(i)}
                        className={`px-3 py-1 rounded-md border ${currentPage === i
                            ? 'bg-indigo-600 text-white border-indigo-600'
                            : 'border-gray-300 hover:bg-gray-50'
                            }`}
                    >
                        {i}
                    </button>
                );
            } else if (
                i === currentPage - 3 ||
                i === currentPage + 3
            ) {
                buttons.push(
                    <span key={i} className="px-2">
                        ...
                    </span>
                );
            }
        }

        // 下一页按钮
        buttons.push(
            <button
                key="next"
                onClick={() => handlePageChange(currentPage + 1)}
                disabled={currentPage === totalPages}
                className="px-3 py-1 rounded-md border border-gray-300 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
            >
                下一页
            </button>
        );

        return buttons;
    };

    return (
        <div className="min-h-screen bg-gray-50 p-8">
            <div className="max-w-7xl mx-auto">
                <div className="flex items-center justify-between mb-6">
                    <div>
                        <h1 className="text-2xl font-bold text-gray-900">人员管理</h1>
                        {currentUser && (
                            <p className="mt-1 text-sm text-gray-500">
                                欢迎回来，{currentUser.display_name}
                            </p>
                        )}
                    </div>
                    <div className="flex space-x-4">
                        <button
                            onClick={showAddUserModal}
                            className="px-4 py-2 text-sm font-medium text-white bg-green-600 rounded-md flex items-center hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
                        >
                            <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                            </svg>
                            添加成员
                        </button>
                        <button
                            onClick={goBack}
                            className="px-4 py-2 text-sm font-medium text-indigo-700 bg-indigo-100 rounded-md hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                        >
                            返回首页
                        </button>
                    </div>
                </div>

                <div className="bg-white shadow-sm rounded-lg overflow-hidden">
                    {tableLoading ? (
                        <div className="flex justify-center items-center h-32">
                            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
                        </div>
                    ) : (
                        <>
                            <table className="min-w-full divide-y divide-gray-200">
                                <thead className="bg-gray-50">
                                    <tr>
                                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户名</th>
                                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">显示名称</th>
                                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">邮箱</th>
                                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
                                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">更新时间</th>
                                    </tr>
                                </thead>
                                <tbody className="bg-white divide-y divide-gray-200">
                                    {users.map(user => (
                                        <tr key={user.id}>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{user.username}</td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{user.display_name}</td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{user.email}</td>
                                            <td className="px-6 py-4 whitespace-nowrap">
                                                <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${user.status === 'active'
                                                    ? 'bg-green-100 text-green-800'
                                                    : 'bg-red-100 text-red-800'
                                                    }`}>
                                                    {user.status === 'active' ? '活跃' : '禁用'}
                                                </span>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                                {dayjs(user.created_at).format('YYYY-MM-DD HH:mm:ss')}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                                {dayjs(user.updated_at).format('YYYY-MM-DD HH:mm:ss')}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                            <div className="px-6 py-4 flex items-center justify-between border-t border-gray-200">
                                <div className="text-sm text-gray-700">
                                    共 {pagination.total} 条记录
                                </div>
                                <div className="flex space-x-2">
                                    {renderPaginationButtons()}
                                </div>
                            </div>
                        </>
                    )}
                </div>
            </div>

            {/* 添加用户弹窗 */}
            {isModalVisible && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4">
                    <div className="bg-white rounded-lg max-w-md w-full p-6">
                        <div className="flex justify-between items-center mb-4">
                            <h3 className="text-lg font-medium text-gray-900">添加新成员</h3>
                            <button
                                onClick={handleCancel}
                                className="text-gray-400 hover:text-gray-500"
                            >
                                <svg className="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>
                        <form onSubmit={handleSubmit}>
                            <div className="space-y-4">
                                <div>
                                    <label htmlFor="username" className="block text-sm font-medium text-gray-700">
                                        用户名
                                    </label>
                                    <input
                                        type="text"
                                        id="username"
                                        name="username"
                                        value={formData.username}
                                        onChange={handleInputChange}
                                        className={`mt-1 block w-full rounded-md shadow-sm ${formErrors.username
                                            ? 'border-red-300 focus:border-red-500 focus:ring-red-500'
                                            : 'border-gray-300 focus:border-indigo-500 focus:ring-indigo-500'
                                            }`}
                                    />
                                    {formErrors.username && (
                                        <p className="mt-1 text-sm text-red-600">{formErrors.username}</p>
                                    )}
                                </div>

                                <div>
                                    <label htmlFor="display_name" className="block text-sm font-medium text-gray-700">
                                        显示名称
                                    </label>
                                    <input
                                        type="text"
                                        id="display_name"
                                        name="display_name"
                                        value={formData.display_name}
                                        onChange={handleInputChange}
                                        className={`mt-1 block w-full rounded-md shadow-sm ${formErrors.display_name
                                            ? 'border-red-300 focus:border-red-500 focus:ring-red-500'
                                            : 'border-gray-300 focus:border-indigo-500 focus:ring-indigo-500'
                                            }`}
                                    />
                                    {formErrors.display_name && (
                                        <p className="mt-1 text-sm text-red-600">{formErrors.display_name}</p>
                                    )}
                                </div>

                                <div>
                                    <label htmlFor="password" className="block text-sm font-medium text-gray-700">
                                        密码
                                    </label>
                                    <input
                                        type="password"
                                        id="password"
                                        name="password"
                                        value={formData.password}
                                        onChange={handleInputChange}
                                        className={`mt-1 block w-full rounded-md shadow-sm ${formErrors.password
                                            ? 'border-red-300 focus:border-red-500 focus:ring-red-500'
                                            : 'border-gray-300 focus:border-indigo-500 focus:ring-indigo-500'
                                            }`}
                                    />
                                    {formErrors.password && (
                                        <p className="mt-1 text-sm text-red-600">{formErrors.password}</p>
                                    )}
                                </div>

                                <div>
                                    <label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700">
                                        确认密码
                                    </label>
                                    <input
                                        type="password"
                                        id="confirmPassword"
                                        name="confirmPassword"
                                        value={formData.confirmPassword}
                                        onChange={handleInputChange}
                                        className={`mt-1 block w-full rounded-md shadow-sm ${formErrors.confirmPassword
                                            ? 'border-red-300 focus:border-red-500 focus:ring-red-500'
                                            : 'border-gray-300 focus:border-indigo-500 focus:ring-indigo-500'
                                            }`}
                                    />
                                    {formErrors.confirmPassword && (
                                        <p className="mt-1 text-sm text-red-600">{formErrors.confirmPassword}</p>
                                    )}
                                </div>

                                <div>
                                    <label htmlFor="email" className="block text-sm font-medium text-gray-700">
                                        邮箱
                                    </label>
                                    <input
                                        type="email"
                                        id="email"
                                        name="email"
                                        value={formData.email}
                                        onChange={handleInputChange}
                                        className={`mt-1 block w-full rounded-md shadow-sm ${formErrors.email
                                            ? 'border-red-300 focus:border-red-500 focus:ring-red-500'
                                            : 'border-gray-300 focus:border-indigo-500 focus:ring-indigo-500'
                                            }`}
                                    />
                                    {formErrors.email && (
                                        <p className="mt-1 text-sm text-red-600">{formErrors.email}</p>
                                    )}
                                </div>
                            </div>

                            <div className="mt-6 flex justify-end space-x-3">
                                <button
                                    type="button"
                                    onClick={handleCancel}
                                    className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                                >
                                    取消
                                </button>
                                <button
                                    type="submit"
                                    disabled={loading}
                                    className={`px-4 py-2 text-sm font-medium text-white bg-indigo-600 rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${loading ? 'opacity-50 cursor-not-allowed' : ''
                                        }`}
                                >
                                    {loading ? (
                                        <span className="flex items-center">
                                            <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
                                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                                            </svg>
                                            创建中...
                                        </span>
                                    ) : '创建用户'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* Toast提示 */}
            {toast.visible && (
                <div className="fixed bottom-6 right-6 z-50 animate-fade-in-up">
                    <div className={`rounded-lg shadow-lg py-2 px-4 flex items-center gap-2 ${toast.type === 'success' ? 'bg-green-500 text-white' :
                        toast.type === 'error' ? 'bg-red-500 text-white' :
                            'bg-blue-500 text-white'
                        }`}>
                        {toast.type === 'success' && (
                            <svg className="w-5 h-5" viewBox="0 0 20 20" fill="currentColor">
                                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                            </svg>
                        )}
                        {toast.type === 'error' && (
                            <svg className="w-5 h-5" viewBox="0 0 20 20" fill="currentColor">
                                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                            </svg>
                        )}
                        {toast.type === 'info' && (
                            <svg className="w-5 h-5" viewBox="0 0 20 20" fill="currentColor">
                                <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2h-1V9z" clipRule="evenodd" />
                            </svg>
                        )}
                        <span className="font-medium">{toast.message}</span>
                    </div>
                </div>
            )}
        </div>
    );
};

export default UserManagement; 